<template>
  <div class="box">
    <CardBox title="经典物种"></CardBox>
    <div class="content-container">
      <div class="media-showcase">
        <div class="media-container">
          <img
                  v-for="(image, index) in images"
                  :key="'img-' + index"
                  :src="image"
                  class="media-item"
                  :class="{ active: currentIndex === index && mediaType === 'image' }"
          >

          <video
                  v-for="(video, index) in videos"
                  :key="'vid-' + index"
                  :src="video.src"
                  class="media-item"
                  :class="{ active: currentIndex === index && mediaType === 'video' }"
                  ref="videoPlayers"
                  @timeupdate="updateProgress(index, $event)"
                  loop
          ></video>

          <div class="media-type-badge">
            {{ mediaType=='video'?'视频':'图片' }} {{ currentIndex + 1 }}/{{ totalMedia }}
          </div>

          <div class="video-controls" v-if="mediaType === 'video'">
            <button class="video-btn" @click="togglePlay">
              {{ isPlaying ? '❚❚' : '▶' }}
            </button>
            <button class="video-btn" @click="restartVideo">↺</button>
            <button class="video-btn" @click="toggleMute">
              {{ isMuted ? '🔇' : '🔊' }}
            </button>
          </div>

          <div class="progress-bar">
            <div class="progress" :style="{ width: progress + '%' }"></div>
          </div>

          <!-- 内部指示器 -->
          <div class="indicators">
            <div
                    v-for="(item, index) in mediaItems"
                    :key="index"
                    class="indicator"
                    :class="{ active: currentIndex === index && mediaType === item.type }"
                    @click="selectMedia(index, item.type)"
            ></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import CardBox from "@/components/Global/CardBox.vue";
import {EventBus} from "../../utils/event-bus";
export default {
  inject: ["imgUrl"], // 注入公共变量
  inject: ["fileUrl"], // 注入公共变量
  components: {
    CardBox,
  },
  data() {
    return {
      curIndex:0,//默认显示的索引
      images:[ 'https://images.unsplash.com/photo-1506744038136-46273834b3fb',
        'https://images.unsplash.com/photo-1452570053594-1b985d6ea890',
        'https://images.unsplash.com/photo-1470071459604-3b5ec3a7fe05'],
      videos:[
        { src: 'https://assets.mixkit.co/videos/preview/mixkit-tree-with-yellow-flowers-1173-large.mp4' },
        { src: 'https://assets.mixkit.co/videos/preview/mixkit-waves-in-the-rocks-1176-large.mp4' }
      ],
      currentIndex:0,
      mediaType:'image',
      autoPlay:true,
      isPlaying:true,
      isMuted:true,
      progress:0,
      videoPlayers:[],
      autoPlayInterval:null,
      pointName:''
    };
  },
  computed:{
    totalMedia(){
      return this.images.length + this.videos.length
    },
    mediaItems(){
      const items = [];
      this.images.forEach(() => items.push({ type: 'image' }));
      this.videos.forEach(() => items.push({ type: 'video' }));
      return items;
    }
  },
  created() {
    EventBus.$on('set-route-item', (message) => {
      this.pointName=message.title;
      this.getItemQJT(message.id);
    })
  },
  mounted() {

  },
  methods:{
    getItemQJT(id){
      this.reset();
      var map={
        observationId:id.toString(),
        orderField:"sort",
        order:"asc"
      };
      this.$api.route.getItemList(map).then(response => {
        if (response) {
          for (let i = 0; i < response.length; i++) {
            switch (response[i].type) {
              case "图片":
                this.images.push(this.fileUrl+response[i].value);
                break;
              case "视频":
                this.videos.push({src:this.fileUrl+response[i].value});
                break;
            }
          }
          this.$nextTick(() => {
            this.inits();
          });

        }
      });
    },
    reset(){
      this.curIndex=0;//默认显示的索引
      this.images=[];
      this.videos=[];
      this.currentIndex=0;
      this.mediaType='image';
      this.autoPlay=true;
      this.isPlaying=true;
      this.isMuted=true;
      this.progress=0;
      this.videoPlayers=[];
      if (this.autoPlayInterval) {
        clearInterval(this.autoPlayInterval);
        this.autoPlayInterval=null;
      }
    },
    inits(){
      this.videoPlayers=this.$refs.videoPlayers;
      if (this.images.length > 0) {
        this.selectMedia(0, 'image');
      } else if (this.videos.length > 0) {
        this.selectMedia(0, 'video');
      }
      // 设置自动播放
      if(!this.autoPlayInterval){
        this.autoPlayInterval = setInterval(() => {
          console.log("===============");
          this.nextMedia();
        }, 10000);
      }

    },
    // 选择特定媒体
    selectMedia(index, type){
      this.currentIndex = index;
      this.mediaType = type;

      // 如果是视频，暂停所有其他视频
      if (type === 'video') {
        this.videoPlayers.forEach((player, i) => {
          if (i === index) {
            player.play().then(() => {
              this.isPlaying = true;
            }).catch(e => {
              console.log("Auto-play was prevented:", e);
            });
          } else {
            player.pause();
          }
        });
      } else {
        // 如果是图片，暂停所有视频
        this.videoPlayers.forEach(player => player.pause());
        this.isPlaying = false;
      }
    },
    // 切换到下一个媒体
    nextMedia(){
      if (this.mediaType === 'image' && this.currentIndex < this.images.length - 1) {
        this.selectMedia(this.currentIndex + 1, 'image');
      } else if (this.mediaType === 'image' && this.currentIndex === this.images.length - 1) {
        if (this.videos.length > 0) {
          this.selectMedia(0, 'video');
        } else {
          this.selectMedia(0, 'image');
        }
      } else if (this.mediaType === 'video' && this.currentIndex < this.videos.length - 1) {
        this.selectMedia(this.currentIndex + 1, 'video');
      } else {
        if (this.images.length > 0) {
          this.selectMedia(0, 'image');
        } else {
          this.selectMedia(0, 'video');
        }
      }
    },
    // 视频控制方法
    togglePlay(){
      if (this.mediaType !== 'video') return;

      const video = this.videoPlayers[this.currentIndex];
      if (video.paused) {
        video.play();
        this.isPlaying = true;
      } else {
        video.pause();
        this.isPlaying = false;
      }
    },
    restartVideo(){
      if (this.mediaType !== 'video') return;

      const video = this.videoPlayers[this.currentIndex];
      video.currentTime = 0;
      video.play();
      this.isPlaying = true;
    },
    toggleMute(){
      if (this.mediaType !== 'video') return;

      const video = this.videoPlayers[this.currentIndex];
      video.muted = !video.muted;
      this.isMuted = video.muted;
    },
    updateProgress(index, event){
      if (this.currentIndex !== index || this.mediaType !== 'video') return;

      const video = event.target;
      const value = (video.currentTime / video.duration) * 100;
      this.progress = value || 0;
    }
  },
  beforeDestroy() {
    if (this.autoPlayInterval) {
      clearInterval(this.autoPlayInterval);
    }
  }
};
</script>

<style lang="scss" scoped>
.content-container {
  padding: 11px 15px;
  height: 406px;
  .title {
    font-size: 18px;
    color: #fff;
    text-align: center;
  }
  .media-showcase {
    width: 100%;
    margin: 0 auto 30px;
    border-radius: 15px;
    overflow: hidden;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
    position: relative;
  }

  .media-container {
    position: relative;
    width: 100%;
    height: 0px;
    padding-bottom: 86.67%; /* 300x200 aspect ratio */
    background: #000;
    overflow: hidden;
  }

  .media-item {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    opacity: 0;
    transition: opacity 0.5s ease;
  }

  .media-item.active {
    opacity: 1;
  }

  /* 内部指示器样式 */
  .indicators {
    position: absolute;
    bottom: 15px;
    left: 0;
    right: 0;
    display: flex;
    justify-content: center;
    gap: 8px;
    z-index: 10;
  }

  .indicator {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.5);
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .indicator.active {
    background: #3498db;
    transform: scale(1.3);
  }

  .video-controls {
    position: absolute;
    bottom: 35px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    gap: 10px;
    background: rgba(0, 0, 0, 0.6);
    padding: 6px 12px;
    border-radius: 30px;
    opacity: 0;
    transition: opacity 0.3s ease;
    z-index: 10;
  }

  .media-container:hover .video-controls {
    opacity: 1;
  }

  .video-btn {
    color: white;
    background: none;
    border: none;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.2s ease;
  }

  .video-btn:hover {
    color: #3498db;
  }

  .media-type-badge {
    position: absolute;
    top: 15px;
    right: 15px;
    background: rgba(0, 0, 0, 0.6);
    color: white;
    padding: 4px 8px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 500;
    z-index: 10;
  }

  .progress-bar {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 3px;
    background: rgba(255, 255, 255, 0.2);
  }

  .progress {
    height: 100%;
    background: #3498db;
    width: 0%;
    transition: width 0.2s ease;
  }

}
</style>